package middleware

import (
	"fmt"
	"github.com/spf13/cast"
	"github.com/zhufuyi/sponge/pkg/logger"
	"net/http"
	"shop/internal/cache"
	"shop/internal/dao"
	"shop/internal/model"
	"shop/internal/tools"
	"time"

	"github.com/zhufuyi/sponge/pkg/gin/response"
	"github.com/zhufuyi/sponge/pkg/jwt"

	"github.com/gin-gonic/gin"
)

type CustBaseWhere struct {
	UserId uint64 `json:"user_id"`
	OpenId string `json:"open_id"`
}

const (
	// HeaderAuthorizationKey http header authorization key
	HeaderAuthorizationKey = "Authorization"
)

func CheckLogin() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		fmt.Println("登录验证中间件")
		// 放行设置
		urlItem := []string{"auth", "swagger"}
		if !tools.InStringArray(ctx.Request.RequestURI, urlItem) {
			// 从请求头中获取Token
			authorization := ctx.GetHeader(HeaderAuthorizationKey)
			if len(authorization) < 20 {
				logger.Warn("authorization is illegal", logger.String(HeaderAuthorizationKey, authorization))
				ctx.JSON(http.StatusOK, response.Result{
					Code: 401,
					Msg:  "缺少用户标识",
				})
				ctx.Abort()
				return
			}
			token := authorization[7:] // remove Bearer prefix
			claim, err := jwt.VerifyToken(token)
			if err != nil {
				ctx.JSON(http.StatusOK, response.Result{
					Code: 401,
					Msg:  "Token已过期",
				})
				ctx.Abort()
				return
			} else if time.Now().Unix() > claim.ExpiresAt {
				ctx.JSON(http.StatusOK, response.Result{
					Code: 401,
					Msg:  "时间超时",
				})
				ctx.Abort()
				return
			} else {
				uid := cast.ToUint64(claim.UID)
				userDao := dao.NewTkMemberDao(
					model.GetDB(),
					cache.NewTkMemberCache(model.GetCacheType()),
				)
				user, err := userDao.GetByID(ctx, uid)
				if err != nil {
					return
				}
				where := &CustBaseWhere{
					UserId: uid,
					OpenId: user.OpenID,
				}
				ctx.Set("baseWhere", where)
			}
		}
		fmt.Printf("ctx.Request.RequestURI : %# v\n", ctx.Request.RequestURI)

		// 前置中间件
		ctx.Next()
	}
}
